package org.gwu.seuss.communication.sockets.ssl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Properties;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class ClientSocket {

	public static SSLSocket createSSLSocket(String propertiesResource,
			String host, int port, char[] storePassword) {

		try {

			Properties properties = Util
					.loadPropertiesFromResource(propertiesResource);
			SystemProperties.initSystemProperties(properties, storePassword,
					storePassword);

			try (InputStream keyStoreInputStream = new FileInputStream(
					properties.getProperty(SystemProperties.KEYSTORE_PROP_KEY))) {

				ManagerPair<KeyManagerFactory, KeyStore> pair = Util
						.getInitKeyFactory(keyStoreInputStream,
								String.copyValueOf(storePassword), "JKS");
				TrustManagerFactory tmf = Util.getInitTrustFactory(pair
						.getStore());
				SSLContext ctx = SSLContext.getInstance("SSL");
				ctx.init(pair.getFactory().getKeyManagers(),
						tmf.getTrustManagers(), null);
				SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory
						.getDefault();
				SSLSocket sslSocket = (SSLSocket) sslsocketfactory
						.createSocket(host, port);
				sslSocket.setEnabledCipherSuites(Util.CIPHERSUITE);
				return sslSocket;

			} catch (Exception ex) {
				throw ex;
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			throw new IllegalStateException("Unable to create client socket",
					ex);
		}
	}

}
